package com.linefly.online_car;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.linefly.online_car.Custom.MyLoading;
import com.linefly.online_car.Custom.ReLogin;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.util.HashMap;

import Util.GaodeToGPS;
import Util.JsonUtil;
import Util.NavigationBarUtil;
import Util.PreferenceUtil;
import Util.ToastUtil;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Response;

public class Lat_Lng_Setting extends AppCompatActivity {
    MapView mMapView = null;
    AMap aMap;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    private MarkerOptions markerOption;
    private String token_str;//用户的token
    Context context = Lat_Lng_Setting.this;
    private String car_id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lat__lng__setting);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        }


        if (NavigationBarUtil.hasNavigationBar(this)) {
            NavigationBarUtil.initActivity(findViewById(android.R.id.content));//解决底部适配
        }

        Intent intent = getIntent();
        car_id = intent.getStringExtra("car_id");
        token_str = PreferenceUtil.getString("token","");

        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);


        if (aMap == null) {
            aMap = mMapView.getMap();


        }
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        // 自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(0);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.gps_point));
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setCompassEnabled(false);
        mUiSettings.setScaleControlsEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setTiltGesturesEnabled(false);





        //地图的点击事件
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(final LatLng latLng) {

                    new SweetAlertDialog(Lat_Lng_Setting.this)
                            .setTitleText("确定添加点?")
                            .setContentText("(" + String.valueOf(latLng.latitude) + "," + String.valueOf(latLng.longitude) + ")")
                            .setConfirmText("确定")
                            .setCancelText("取消")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sDialog) {
                                    sDialog.dismissWithAnimation();
                                    LatLonPoint latLonPoint = GaodeToGPS.toGPSPoint(latLng.latitude,latLng.longitude);

                                    MyLoading.show(context);
                                    try {
                                        String url = getString(R.string.url) + "/device/search";

                                        OkHttpUtils.get(url)
                                                .connTimeOut(10000)
                                                .params("token",token_str)
                                                .params("id",car_id)
                                                .params("lat",latLonPoint.getLatitude())
                                                .params("lng",latLonPoint.getLongitude())
                                                .execute(new StringCallback() {
                                                    @Override
                                                    public void onSuccess(String s, okhttp3.Call call, Response response) {
                                                        MyLoading.cancel();
                                                        Object object = null;
                                                        object = JsonUtil.jsonParse(s);
                                                        if(object instanceof HashMap) {
                                                            final HashMap hashMap = (HashMap) object;
                                                            if (hashMap.containsKey("err")) ;
                                                            int err = Integer.valueOf(hashMap.get("err").toString());
                                                            if (err == 0) {
                                                                ToastUtil.toast(context,"成功");
                                                                finish();

                                                            }else if(err < 0){
                                                                ReLogin.login(context);
                                                            }else {
                                                                ToastUtil.toast(context,hashMap.get("msg").toString());
                                                            }




                                                        }

                                                    }
                                                    @Override
                                                    public void onError(Call call, Response response, Exception e) {

                                                        MyLoading.cancel();
                                                        Toast.makeText(context, "连接服务器失败", Toast.LENGTH_LONG).show();
                                                        e.printStackTrace();
                                                    }
                                                });

                                    }catch (Exception e) {
                                        e.printStackTrace();
                                    }


                                }
                            })
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            })
                            .show();




            }
        });

    }

    public void click_back(View view){
        finish();
    }
}
